<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2018-03-08
 * @Time: 16:01
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： AskStatus.php
 */
namespace app\admin\command;

use app\common\model\UserCreditRecord;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;

/**
 * 【定时任务】每一小时执行一次
 * 更新已过期未回答的付费问答状态并返还用户积分
 *
 * @author zhengkai
 * @date 2018-03-08
 * @version 1.4
 *
 * Class AskStatus
 * @package app\admin\command
 */
class AskStatus extends Command {
    /**
     * 命令：php think askStatus
     */
    protected function configure()
    {
        $this->setName('askStatus')->setDescription('付费问答状态更新与过期数据用户积分返还');
    }

    protected function execute(Input $input, Output $output)
    {
        $sql = <<<SQL
select * from ask;
SQL;
        $data = Db::query($sql);

        foreach ($data as $key=>$val) {
            $askTime = strtotime($val['ask_time']);

            // 计算提问时间距离当前时间的小时数
            $hour = floor((time()-$askTime)/60/60);

            if ($val['ask_status']==0 && $hour>=48) {
                // 标记问答状态为过期
                Db::query("update ask set ask_status=3 where ask_id=:ask_id", ['ask_id'=>$val['ask_id']]);

                // 返还积分给提问用户
                $user = Db::query("select id,mobile,credit from users where id=:uid", ['uid'=>$val['ask_user']]);
                $user = $user[0];

                $userNewCredit = ($user['credit']+$val['ask_credit']);
                Db::query("update users set credit={$userNewCredit} where id=:uid", ['uid'=>$val['ask_id']]);
                UserCreditRecord::record($val['ask_user'], UserCreditRecord::CHANGE_TYPE_ASK_TIMEOUT_REFUND, $val['ask_credit'], '付费问答超时积分返还', ['ask_id' => $val['ask_id']]);

                echo "已标识用户【{$user['mobile']}】的提问【{$val['ask_id']}】为未回答过期状态，并返回积分【{$val['ask_credit']}】"."\r\n";
            }
        }
    }
}